package org.example.day10;

import java.util.Date;

/**
 * 3.3.1.1 ThreadLocal的隔离性
 */
public class MyThread2 {
    public static ThreadLocal<Date> t1 = new ThreadLocal<>();

    public static void main(String[] args) {
        try {
            Thread2A ta = new Thread2A();
            ta.start();
            Thread.sleep(1000);
            Thread2B tb = new Thread2B();
            tb.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread2A extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; i++) {
                //第一次进来为null,之后进来都不为null
                if(MyThread2.t1.get() == null){
                    MyThread2.t1.set(new Date());
                }
                System.out.println("线程A：" + MyThread2.t1.get().getTime());
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread2B extends Thread{
    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; i++) {
                if(MyThread2.t1.get() == null){
                    MyThread2.t1.set(new Date());
                }
                System.out.println("线程B：" + MyThread2.t1.get().getTime());
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

